package com.miyake.client.tools;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.miyake.client.DataService;
import com.miyake.client.DataServiceAsync;
import com.miyake.client.datamanage.NodeProperty;
import com.google.gwt.user.client.ui.VerticalPanel;

public abstract class ItemListDialog extends DialogBox {
	protected DataServiceAsync service = DataService.Util.getInstance();
	private String selectedKey;
	private Grid grid;
	
	abstract protected void getContentList(String nodeKey);
	abstract protected void getContent(String key, Image image);
	
	public ItemListDialog(String nodeKey) {
		setHTML("Selection");
		
		VerticalPanel verticalPanel = new VerticalPanel();
		setWidget(verticalPanel);
		verticalPanel.setSize("100%", "100%");
		
		verticalPanel.add(getHeader(nodeKey));
		
		grid = new Grid();
		verticalPanel.add(grid);
		getContentList(nodeKey);
		
		Button close = new Button("Close");
		verticalPanel.add(close);
		close.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				hide(true);
			}
		});
	}

	protected void showList(List<NodeProperty> result) {
		int columns = 4;
		int rows = result.size() / columns + 1;
		grid.resize(rows, columns);
		int row = 0;
		int column = 0;

		for (NodeProperty node : result) {
			VerticalPanel p = new VerticalPanel();
			final Image image = new ClickableImage();
			image.setTitle(node.getKey());
			image.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					selectedKey = image.getTitle();
					hide(false);
				}
			});
			p.add(image);
			grid.setWidget(row, column++, p);
			if (column >= columns) {
				column = 0;
				row++;
			}		
			ClickableLabel label = new ClickableLabel();
			label.setText(node.getName());
			p.add(label);
			p.setCellHorizontalAlignment(label, HasHorizontalAlignment.ALIGN_CENTER);
			getContent(node.getKey(), image);
		}
	}

	public String getSelectedKey() {
		return selectedKey;
	}
	
	protected ComplexPanel getHeader(String nodeKey) {return null;}
}
